<?php
//前台用户注册

namespace app\app\controller;

use think\exception\HttpResponseException;
use think\Controller;

use think\Db;
use think\Request;

class Vote extends Controller
{
    public function responseJson($data = [],$code = 0)
    {
        $msg =  $GLOBALS['ERR_CODE'][$code] ? $GLOBALS['ERR_CODE'][$code] : '';
        throw new HttpResponseException(json(['code'=>$code,'msg'=> $msg,'data'=>$data]));
    }

    //人气值投票
    public function vote()
    {
        if (Request::instance()->isPost()) {
            $ip = Request::instance()->param('ip', null);//获取ip
            $id = Request::instance()->param('id', null);//品牌id
            if (empty($id)) {
                $this->responseJson([], 3035);
            }

            //今天凌晨时间戳
            $startTime = strtotime(date('Ymd'));
            //第二天0点时间戳
            $time = $startTime + 86400;

            //判断该IP今天是否投过该品牌
            $voteData = Db::name('vote')->where('mid',$ip)->where('eid',$id)->where('addTime','>',$startTime)->where('addTime','<',$time)->find();
            if (!empty($voteData)){
                $this->responseJson([],3047);
            }
            $enterpriseData = Db::name('enterprise')->where('id',$id)->find();
            if (!$enterpriseData){
                $this->responseJson([],1000);
            }
            //人气值增加1
            $tmp = Db::name('enterprise')->where('id', $id)->setInc('Popularity', 1);
            if (!$tmp) {
                $this->responseJson([], 3043);
            }
            $arr  = [
                'mid' => $ip,
                'eid' => $id,
                'addTime' => time()
            ];
            //记录投票
            $data = Db::name('vote')->insert($arr);
            if (!$data){
                $this->responseJson([],3044);
            }
            $this->responseJson([],0);
        }
        $this->responseJson([], 1000);
    }
}
